package com.itobase.statusDetect.Controller;

import com.itobase.statusDetect.Model.Organization;
import com.itobase.statusDetect.Repository.OrganizationRepository;
import com.itobase.statusDetect.Service.OrganizationService;
import com.itobase.statusDetect.Util.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.InvalidParameterException;
import java.util.List;

/**
 * @author htyu
 * @date 2019/2/24
 */
@RestController
@RequestMapping("organization")
public class OrganizationController {

    @Autowired
    OrganizationService organizationService;

    @Autowired
    OrganizationRepository organizationRepository;


    @PostMapping("create")
    public Message create(@RequestParam(required = false) String fatherID ,@RequestParam String name){
        try {
            return Message.success(organizationService.create(fatherID, name));
        }catch (InvalidParameterException e){
            return Message.error(-1,"组织名重复,请勿重复添加");
        }catch (RuntimeException e){
            return Message.error(-2,"上一级组织不存在");
        }
    }

    @PutMapping("rename")
    public Message rename(@RequestParam String id,@RequestParam String name){
        try{
            return Message.success(organizationService.rename(id,name));
        }catch (InvalidParameterException e){
            return Message.error(-1,"组织名重复,请勿重复添加");
        }catch (RuntimeException e){
            return Message.error(-2,"该组织不存在");
        }
    }

    @DeleteMapping("delete")
    public Message delete(@RequestParam String id){
        List<Organization> list = organizationRepository.findByFowardID(id);
        if(list.size()==0){
            organizationRepository.deleteById(id);
            return Message.success("删除成功");
        }else{
            return Message.error(-1,"存在下级组织架构，不能直接删除");
        }
    }
}
